package com.witmore.neutron.ai.mcp.server.trading.service;

import com.jk.aliyun.oss.JkOssClient;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.UUID;

/**
 * OSS文件上传服务
 *
 * @author 豆子高
 * @date 2025-01-20
 */
@Slf4j
@Service
public class OssUploadService {

    @Autowired
    private JkOssClient jkOssClient;

    /**
     * 上传PDF报告到OSS
     *
     * @param pdfBytes  PDF文件字节数组
     * @param stockCode 股票代码
     * @param userId    用户ID
     * @return OSS文件访问URL
     */
    public String uploadStockAnalysisReport(byte[] pdfBytes, String stockCode, Long userId) {
        try {
            // 生成文件名
            String fileName = generatePdfFileName(stockCode, userId);

            log.info("开始上传PDF报告到OSS - 文件名: {}, 大小: {} bytes", fileName, pdfBytes.length);

            // 使用JK组件库的OssClient上传文件
            return jkOssClient.uploadFile(
                    fileName,
                    pdfBytes
            );

        } catch (Exception e) {
            log.error("PDF报告上传失败 - 股票代码: {}, 用户ID: {}, 错误: {}",
                    stockCode, userId, e.getMessage(), e);
            throw new RuntimeException("PDF报告上传失败: " + e.getMessage(), e);
        }
    }

    /**
     * 上传HTML报告到OSS
     *
     * @param htmlContent HTML内容字符串
     * @param stockCode   股票代码
     * @param userId      用户ID
     * @return OSS文件访问URL
     */
    public String uploadHtmlReport(String htmlContent, String stockCode, Long userId) {
        try {
            // 将HTML字符串转换为字节数组
            byte[] htmlBytes = htmlContent.getBytes("UTF-8");
            
            // 生成HTML文件名
            String fileName = generateHtmlFileName(stockCode, userId);

            log.info("开始上传HTML报告到OSS - 文件名: {}, 大小: {} bytes", fileName, htmlBytes.length);

            // 使用JK组件库的OssClient上传文件
            return jkOssClient.uploadFile(
                    fileName,
                    htmlBytes
            );

        } catch (Exception e) {
            log.error("HTML报告上传失败 - 股票代码: {}, 用户ID: {}, 错误: {}",
                    stockCode, userId, e.getMessage(), e);
            throw new RuntimeException("HTML报告上传失败: " + e.getMessage(), e);
        }
    }

    /**
     * 生成PDF文件名
     * 格式: stock-analysis/{stockCode}/stock_{stockCode}_{userId}_{timestamp}_{uuid}.pdf
     */
    private String generatePdfFileName(String stockCode, Long userId) {
        String timestamp = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMdd_HHmmss"));
        String uuid = UUID.randomUUID().toString().replace("-", "").substring(0, 8);

        return String.format("stock-analysis/%s/stock_%s_%s_%s_%s.pdf",
                stockCode,
                stockCode,
                userId != null ? userId : "anonymous",
                timestamp,
                uuid);
    }

    /**
     * 生成HTML文件名
     * 格式: stock-reports/{stockCode}/report_{stockCode}_{userId}_{timestamp}_{uuid}.html
     */
    private String generateHtmlFileName(String stockCode, Long userId) {
        String timestamp = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMdd_HHmmss"));
        String uuid = UUID.randomUUID().toString().replace("-", "").substring(0, 8);

        return String.format("stock-reports/%s/report_%s_%s_%s_%s.html",
                stockCode,
                stockCode,
                userId != null ? userId : "anonymous",
                timestamp,
                uuid);
    }

    /**
     * 生成通用文件名（保留原方法供向后兼容）
     * 格式: stock_{stockCode}_{userId}_{timestamp}_{uuid}.pdf
     */
    private String generateFileName(String stockCode, Long userId) {
        return generatePdfFileName(stockCode, userId);
    }

}
